package com.et.protocol.core;

import android.util.Log;

import androidx.annotation.Keep;

import com.et.logger.ELog;
import com.et.logger.TAGS;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@Keep
public class SerialNative {

    private static final String TAG = "SerialPort";

    /*
     * Do not remove or rename the field mFd: it is used by native method close();
     */
    @Keep
    private FileDescriptor mFd;
    private FileInputStream mFileInputStream;
    private FileOutputStream mFileOutputStream;

    SerialNative(File device, int baud, int flags) throws SecurityException, IOException {

        /* Check access permission */
        if (!device.canRead() || !device.canWrite()) {
            try {
                /* Missing read/write permission, trying to chmod the file */
                // 获取su读写权限
                Process su;
                File f = new File("/system/bin/su");
                if (!f.exists()) {
                    f = new File("/system/xbin/su");
                    if (!f.exists()) {
                        ELog.Companion.d(TAGS.protocol, "su not fond");
                        return;
                    }
                }
                su = Runtime.getRuntime().exec(f.getAbsolutePath());
                String cmd = "chmod 666 " + device.getAbsolutePath() + "\n"
                        + "exit\n";
                su.getOutputStream().write(cmd.getBytes());
                if ((su.waitFor() != 0) || !device.canRead() || !device.canWrite()) {
                    throw new SecurityException();
                }
            } catch (Exception e) {
                Log.d(TAG, "SerialPort: Exception: no permission to open serialPort");
                throw new SecurityException();
            }
        }
        mFd = open(device.getAbsolutePath(), baud, flags);
        if (mFd == null) {
            Log.e(TAG, "Exception: no serialPort, open failed");
            throw new IOException();
        }
        mFileInputStream = new FileInputStream(mFd);
        mFileOutputStream = new FileOutputStream(mFd);
    }

    // Getters and setters
    InputStream getInputStream() {
        return mFileInputStream;
    }

    OutputStream getOutputStream() {
        return mFileOutputStream;
    }

    // JNI
    @Keep
    private native static FileDescriptor open(String path, int baud, int flags);

    @Keep
    public native void close();

    static {
        System.loadLibrary("protocol-lib");
    }
}
